import React from 'react';
import produce from 'immer';
import Upload from '@/zero/components/Upload';

/**
 * 简易 Upload => 全部替换式上传
 */
const Index = (props) => {
  const {
    disabled = false,
    multiple = false,
    labelKey = 'name',

    value,
    onChange,

    // eslint-disable-next-line
    render = (newValue, newOnChange) => {
      const toText = (item) => {
        const text =
          typeof item === 'string'
            ? item
            : item &&
              (item[labelKey] || item.fileName || item.filename || item.file_name || 'Undefined');
        return (
          <div style={{ position: 'relative', marginTop: 5 }} key={text}>
            {text}
          </div>
        );
      };
      return Array.isArray(newValue) ? newValue.map((item) => toText(item)) : toText(value);
    },

    ...rest
  } = props;

  const newProps = produce({}, (draftState) => {
    if (multiple) {
      draftState.onAllComplete = (files) => {
        onChange(files);
      };
    } else {
      draftState.onFileComplete = (file) => {
        onChange(file);
      };
    }
    return draftState;
  });

  return (
    <>
      <Upload disabled={disabled} multiple={multiple} {...rest} {...newProps} />

      {render(value, onChange)}
    </>
  );
};

Index.displayName = 'SimpleUpload';
export default Index;
